package me.xue.communityhealth.admin.controller;

import me.xue.communityhealth.model.DrugUnit;
import me.xue.communityhealth.service.DrugUnitService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
public class DrugUnitController {

    private final DrugUnitService drugUnitService;

    @Autowired
    public DrugUnitController(DrugUnitService drugUnitService) {
        this.drugUnitService = drugUnitService;
    }

    @GetMapping("/drugUnits")
    public String allDrugUnits(Model model) {
        List<DrugUnit> drugUnits = drugUnitService.findAll();
        model.addAttribute("drugUnits", drugUnits);
        return "drug_units";
    }

    @GetMapping("/drugUnit/add")
    public String addDrugUnitPage(Model model) {
        model.addAttribute("drugUnit", new DrugUnit());
        return "drug_unit_edit";
    }

    @PostMapping("/drugUnit")
    public String addDrugUnit(DrugUnit drugUnit) {
        if (drugUnitService.save(drugUnit) == 1) {
            return "redirect:/drugUnits";
        }
        return "drug_unit_edit";
    }

    @DeleteMapping("/drugUnit/{id:\\d+}")
    @ResponseBody
    public String deleteDrugUnit(@PathVariable("id") Integer id) {
        if (drugUnitService.delete(id) == 1) {
            return "success";
        }
        return "fail";
    }

    @GetMapping("/drugUnit/{id:\\d+}/edit")
    public String updateDrugUnitPage(@PathVariable("id") Integer id, Model model) {
        DrugUnit drugUnit = drugUnitService.findOne(id);
        model.addAttribute("drugUnit", drugUnit);
        return "drug_unit_edit";
    }

    @PutMapping("/drugUnit")
    public String updateDrugUnit(DrugUnit drugUnit) {
        if (drugUnitService.update(drugUnit) == 1) {
            return "redirect:/drugUnits";
        }
        return "drug_unit_edit";
    }


}
